<template>
  <div class="quantity-region-container">
    <div class="text-gradient">
      <h2>设备数量地区分布</h2>
    </div>

    <div id="quantity-region-echart-div"></div>
  </div>
</template>

<script>
import echarts from 'echarts'
import { provinceDeviceCount } from '@/api/homePage'

export default {
  name: 'quantityAndRegion',
  data() {
    return {
      chart: null,
      data: []
    }
  },

  mounted() {
    this.doQuery()
    window.addEventListener('resize', this.resizeChart) // 添加窗口 resize 事件监听
  },

  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
      this.chart = null
    }
    window.removeEventListener('resize', this.resizeChart) // 移除事件监听
  },

  methods: {
    async doQuery() {
      try {
        const {
          data: { data }
        } = await provinceDeviceCount()

        this.data = data.map(item => ({
          value: item.deviceCount,
          name: item.name
        }))

        this.$nextTick(() => {
          this.initChart()
        })
      } catch (error) {
        console.error('数据获取失败:', error)
      }
    },

    initChart() {
      this.chart = echarts.init(
        document.getElementById('quantity-region-echart-div')
      )

      const totalValue = this.data.reduce((sum, item) => sum + item.value, 0)

      const option = {
        tooltip: {
          trigger: 'item',
          show: false
        },
        legend: {
          top: '5%',
          left: '6%',
          orient: 'vertical',
          textStyle: {
            color: 'rgba(255,255,255,0.65)',
            fontSize: 16
          },
          formatter: name => {
            const targetData = this.data.find(item => item.name === name)
            const percentage = Math.round((targetData.value / totalValue) * 100)
            return `${name} | ${percentage}%  ${targetData.value}`
          }
        },
        series: [
          {
            name: 'quantity',
            type: 'pie',
            radius: ['30%', '45%'],
            center: ['68%', '26%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 30,
              borderColor: '#081744',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '12',
                fontWeight: 'bold',
                color: '#fff',
                formatter: '{b}\n{d}%，{c}'
              }
            },
            labelLine: {
              show: false
            },
            data: this.data
          }
        ],
        color: [
          '#005DD7',
          '#188FFF',
          '#59CCFF',
          '#13C1C1',
          '#27A97D',
          '#FACB14'
        ]
      }

      this.chart.setOption(option)
    },

    resizeChart() {
      if (this.chart) {
        this.chart.resize() // 在窗口大小变动时调用
      }
    }
  }
}
</script>

<style lang="scss" scoped>
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.quantity-region-container {
  height: 390px;
  width: 100%;
}

#quantity-region-echart-div {
  height: 100%;
  width: 100%;
}

.text-gradient {
  color: #fff;
  display: flex;
  line-height: 70px;
  align-items: center;
  justify-content: center;
}
</style>
